package com.sky.service.impl;


import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //创建一个TurnoverReportVO对象，用于封装返回数据
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        //1.得到日期的集合并拼接成一个字符串
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateListString = StringUtils.join(dateList, ",");
        //2.遍历日期集合，通过调用mapper接口，得到每天营业额，封装到turnoverList中，然后拼接成字符串
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = reportMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        String turnoverListString = StringUtils.join(turnoverList, ",");
        //3.赋值给turnoverReportVO对象
        turnoverReportVO.setDateList(dateListString);
        turnoverReportVO.setTurnoverList(turnoverListString);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        //建立日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateListString = StringUtils.join(dateList, ",");
        //建立每日增长人员数量的集合
        List<Long> newUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            long count = reportMapper.userCountByMap(map);
            newUserList.add(count);
        }
        String newUserListString = StringUtils.join(newUserList, ",");
        //建立这一日总人数的集合
        List<Long> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList){
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            long sum = reportMapper.sumUserDaliyByMap(endTime);
            totalUserList.add(sum);
        }
        String totalUserListString = StringUtils.join(totalUserList, ",");
        //赋值给返回对象
        userReportVO.setDateList(dateListString);
        userReportVO.setNewUserList(newUserListString);
        userReportVO.setTotalUserList(totalUserListString);
        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //创建返回体
        OrderReportVO orderReportVO = new OrderReportVO();
        //创建日期集合和构建大那会日期字符串
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateListString = StringUtils.join(dateList, ",");
        //创建每日订单数的集合和返回字符串
        List<Integer> orderCountList = new ArrayList();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer count = reportMapper.sumOrdersByMap(map);
            orderCountList.add(count);
        }
        String orderCountListString = StringUtils.join(orderCountList, ",");
        //创建每日有效订单数的集合和返回字符串
        List<Integer> validOrderCountList = new ArrayList();
        for (LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer count = reportMapper.sumOrderValidsByMap(map);
            validOrderCountList.add(count);
        }
        String orderCountValidListString = StringUtils.join(validOrderCountList, ",");
        //得到这个时间段的有效和总数（包含无效）的订单总数
        Integer totalOrderCount = 0;
        Integer validtotalOrderCount = 0;
        for (Integer count : orderCountList){
            totalOrderCount += count;
        }
        for (Integer count : validOrderCountList){
            validtotalOrderCount += count;
        }
        //订单完成率
        Double orderCompletionRate = validtotalOrderCount.doubleValue() / totalOrderCount;
        orderReportVO.setDateList(dateListString);
        orderReportVO.setOrderCountList(orderCountListString);
        orderReportVO.setValidOrderCountList(orderCountValidListString);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validtotalOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //首先拿到规定点单时间内的订单ID
        List<Long> orderIds = reportMapper.listOrdersIdByTime(beginTime, endTime);
        if (orderIds == null || orderIds.isEmpty()) {
            return salesTop10ReportVO;
        }
        List<DishNumberVO> dishNumberVOList = reportMapper.getSalesTop10(orderIds);
        //创建集合，一个名字，一个数量
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (DishNumberVO dishNumberVO : dishNumberVOList) {
            nameList.add(dishNumberVO.getName());
            numberList.add(dishNumberVO.getCount());
        }
        String nameListString = StringUtils.join(nameList, ",");
        String numberListString = StringUtils.join(numberList, ",");
        salesTop10ReportVO.setNameList(nameListString);
        salesTop10ReportVO.setNumberList(numberListString);
        return salesTop10ReportVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        //一.首先把表格的模版先导入进来
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/businessData.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        //二.然后把最近30天的数据导入进去
        //1.先拿到日期区间
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //2.然后再把时间区间填入表格中
        sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
        //3.再把概览数据填入表格中
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);
        sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
        //4.再把订单数据填入表格中
        for (int i = 0;i<30;i++){
            LocalDate date = begin.plusDays(i);
            sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
            LocalDateTime beginTime01 = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime01 = LocalDateTime.of(date, LocalTime.MAX);
            BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(beginTime01, endTime01);
            sheet.getRow(7+i).getCell(2).setCellValue(businessDataVO1.getTurnover());
            sheet.getRow(7+i).getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
            sheet.getRow(7+i).getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
            sheet.getRow(7+i).getCell(5).setCellValue(businessDataVO1.getUnitPrice());
            sheet.getRow(7+i).getCell(6).setCellValue(businessDataVO1.getNewUsers());
        }

        //三，导出订单
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        //四，关闭资源
        workbook.close();
        outputStream.close();
        inputStream.close();
    }
}
